//
//  WYPayMethod.m
//  WithYou
//
//  Created by edz on 2020/7/27.
//  Copyright © 2020 郭子一. All rights reserved.
//

#import "WYPayMethodManager.h"

#define WXUrlSchemeIdentifier @"weixin"
#define AlipayUrlSchemeIdentifier @"alipay"
#define WXPayPrefix @"wx35f0313004f4de63://pay"
#define WXLoginPrefix @"wx35f0313004f4de63://oauth"
#define WXAppId @"wx35f0313004f4de63"
#define WXUniversalLink @"https://app.uniqueyn.cn/"
#define WXAppSecret @"6e3f6c463be6f97152cff87b087403fb"
static NSString * AlipayUrlScheme = nil;

@implementation PayAlipayData
@end

@implementation PayWeChatData
@end

@interface WYPayMethodManager ()<WXApiDelegate>

@property (nonatomic, copy) PayCompleteCallBack payCompleteBlock;

@end

@implementation WYPayMethodManager

static NSString * JSSQueryUrlScheme(NSString *identifier) {
    NSDictionary *infoDic = [NSBundle mainBundle].infoDictionary;
    NSArray *urlTypeDicArr = infoDic[@"CFBundleURLTypes"];
    for (NSDictionary *urlTypeDic in urlTypeDicArr) {
        if ([urlTypeDic[@"CFBundleURLName"] isEqualToString:identifier]) {
            return [urlTypeDic[@"CFBundleURLSchemes"] firstObject];
            break;
        }
    }
    return @"";
}

+ (instancetype)sharedManager {
    static WYPayMethodManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}

///初始化部分
+ (void)ready
{
    [self readyWeXin];
    [self readyAlipay];
}

+ (void)readyWeXin {
    [WXApi registerApp:WXAppId universalLink:WXUniversalLink];
}

+ (void)readyAlipay {
    AlipayUrlScheme = JSSQueryUrlScheme(AlipayUrlSchemeIdentifier);
}

+ (BOOL)handleUrl:(NSURL *)url
{
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            // 处理支付宝支付回调结果
            [self _handleAlipayResult:resultDic];
        }];
    } else if ([url.description hasPrefix:WXPayPrefix]) {
        // 微信支付
        return [WXApi handleOpenURL:url delegate:[WYPayMethodManager sharedManager]];
    } else if ([url.description hasPrefix:WXLoginPrefix]) {
        // 微信登录
        return [WXApi handleOpenURL:url delegate:[WYPayMethodManager sharedManager]];
    }
    return YES;
}

+ (void)_handleAlipayResult:(NSDictionary *)result {
    NSString *resultStatus = result[@"resultStatus"];
    PayResultCode code = PayResultCodeFailure;
    NSString *message = @"";
    NSString *resultString = result[@"result"];
    if ([resultStatus isEqualToString:@"9000"]) {
        // 成功
        code = PayResultCodeSuccess;
        message = @"支付成功";
    } else if ([resultStatus isEqualToString:@"8000"]) {
        code = PayResultCodeProcessing;
        message = @"支付失败";
    } else if ([resultStatus isEqualToString:@"6001"]) {
        code = PayResultCodeUserCancel;
        message = @"付款已取消";
    }
    if ([WYPayMethodManager sharedManager].payCompleteBlock) {
        [TipView showMessage:message];
        [WYPayMethodManager sharedManager].payCompleteBlock(resultString, message, code);
        [WYPayMethodManager sharedManager].payCompleteBlock = nil;
    }
}

///是否安装微信客户端
+ (BOOL)isInstallWeChat
{
    return [WXApi isWXAppInstalled];
}

///是否安装支付宝客户端
+ (BOOL)isInstallAlipay
{
    NSURL * myURL_APP_A = [NSURL URLWithString:@"uniquemobilealipay://"];
    return ([[UIApplication sharedApplication] canOpenURL:myURL_APP_A])?:NO;
}

///支付
+ (void)useAlipayPayOrderForOrderData:(PayAlipayData *)orderData callBack:(PayCompleteCallBack)callBack
{
    [WYPayMethodManager sharedManager].payCompleteBlock = callBack;
    NSString *orderString = orderData.orderSpec;
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:AlipayUrlScheme callback:^(NSDictionary *resultDic) {
        [self _handleAlipayResult:resultDic];
    }];
}

+ (void)useWeChatPayOrderForOrderData:(PayWeChatData *)orderData callBack:(PayCompleteCallBack)callBack
{
    [WYPayMethodManager sharedManager].payCompleteBlock = callBack;
    PayReq *req = [[PayReq alloc] init];
    req.partnerId = orderData.partnerId;
    req.prepayId = orderData.prepayId;
    req.package = orderData.package;
    req.nonceStr = orderData.nonceStr;
    req.timeStamp = orderData.timeStamp;
    req.sign = orderData.sign;
    [WXApi sendReq:req completion:nil];
    
}

#pragma mark - WXApiDelegate
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) { // 支付结果
        PayResp *payResp = (PayResp *)resp;
        PayResultCode code = PayResultCodeFailure;
        NSString *message = nil;
        if (payResp.errCode == WXSuccess) {
            // 支付成功
            code = PayResultCodeSuccess;
            message = @"支付成功";
        } else if (payResp.errCode == WXErrCodeUserCancel) {
            // 用户取消
            code = PayResultCodeUserCancel;
            message = @"付款已取消";
        } else {
            // 失败
            code = PayResultCodeFailure;
            message = @"支付失败";
        }
        if ([WYPayMethodManager sharedManager].payCompleteBlock) {
            [TipView showMessage:message];
            [WYPayMethodManager sharedManager].payCompleteBlock(payResp.returnKey, message, code);
            [WYPayMethodManager sharedManager].payCompleteBlock = nil;
        }
    } else if ([resp isKindOfClass:[SendAuthResp class]]) { // 登录授权
        SendAuthResp *aresp = (SendAuthResp *)resp;
        if (aresp.errCode != 0 ) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [TipView showMessage:@"微信授权失败"];
            });
            return;
        }
        //授权成功获取 OpenId
        NSString *code = aresp.code;
        [self getWeiXinOpenId:code];
    }
}

//通过code获取access_token，openid，unionid
- (void)getWeiXinOpenId:(NSString *)code{
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAppId,WXAppSecret,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
            [TipView showMessage:@"微信授权失败"];
            return ;
        }
        
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"token、openID字典===%@",dic);
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
        //微信返回信息后,会跳到登录页面,添加通知进行其他逻辑操作
        [[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatOK" object:nil userInfo:@{@"Openid":openid}];
        //         获取微信用户信息
        [self getUserInfoWithAccessToken:access_token WithOpenid:openid];
        
    });
}

-(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid
{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 获取用户信息失败
            if (!data) {
                [TipView showMessage:@"微信授权失败"];
                return ;
            }
            
            // 获取用户信息字典
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //用户信息中没有access_token 我将其添加在字典中
            [dic setValue:access_token forKey:@"token"];
            NSLog(@"用户信息字典:===%@",dic);
            //保存改用户信息(我用单例保存)
            
//          //微信返回信息后,会跳到登录页面,添加通知进行其他逻辑操作
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatOK" object:nil];
            
        });
        
    });
    
}

@end
